<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/5/25
 * Time: 17:29
 */

namespace Home\Controller;
use Think\Controller;

class OrderController extends CommonController
{
    private $Cart = '';
    private $userID = '';
    private $Goods = '';
    private $userAddress = '';
    private $Region = '';
    private $orderInfo = '';
    private $orderGoods = '';
    private $Seller='';

    function __construct()
    {
        parent::__construct();

        $this->Cart = D('Cart');
        $this->Goods = D('Goods');
        $this->userID = session("userID");
        $this->userAddress = D('UserAddress');
        $this->Region = D('Region');
        $this->orderInfo = D("Order_info");
        $this->orderGoods = D("Order_goods");
        $this->Seller = D('Seller');
    }

    //   下述的优惠，至表示在微信支付时
    function cart()
    {
        $this->Cart->where("number=0")->delete();   //删除掉购物车中数量为“0”的记录
        $arr = $this->Cart->where("user_id=" . $this->userID)->select();

        if(empty($arr))
        {
            //如果购物车中的商品为空
            $this->success("您还没有选择商品",U('Index/lbs'));
        }

        $countPrice = '';
        $countPromotePrice = '';
        foreach($arr as $key => $r){
            $brr = $this->Goods->where("id=" . $r['goods_id'])->find();
            $arr[$key]['thumb'] = $brr['thumb'];
            $arr[$key]['productName'] = $brr['name'];
            $arr[$key]['shop_price'] = $brr['shop_price'];
            $arr[$key]['price'] = $r['number'] * $r['shop_price'];
            $arr[$key]['promotePrice'] = $brr['promote_price'];   // 单个商品优惠的价格
            $arr[$key]['countPromotePrice'] = $r['number'] * $brr['promote_price'];     // 此商品的个数乘以他的优惠价格
            $countPromotePrice += $arr[$key]['countPromotePrice'];   //   计算出总共的优惠价格
            $countPrice += $arr[$key]['price'];   // 总价格
        }

        //查找出用户默认地址
        $cond['user_id'] = $this->userID;
        $cond['sign_build'] = "1";
        $crr = $this->userAddress->where($cond)->find();

//        if (!empty($crr['province'])) {      // 省如果为空， 泽不需要到数据空中查找
//            $c1 = $this->Region->where("region_id=" . $crr['province'])->find();
//            $crr['provinceName'] = $c1['region_name'];
//        } else {
//            $this->error("地址有误,请重新填写!",U('Users/address'));
//            $crr['provinceName'] = "";
//        }
//
        if (!empty($crr['city'])) {       //  同上的道理
            $c2 = $this->Region->where("region_id=" . $crr['city'])->find();
            $crr['cityName'] = $c2['region_name'];
        } else {
            $this->error("地址有误,请重新填写!",U('Users/address'));
            $crr['cityName'] = "";
        }


        if($crr['consignee']=="")
        {
            $this->error("地址信息中没有填写姓名!",U('Users/address'));
        }

        if($crr['tel']=="")
        {
            $this->error("地址信息中没有填写电话!",U('Users/address'));
        }

        if (!empty($crr['zone'])) {     // 同上的道理
            $c3 = $this->Region->where("region_id=" . $crr['zone'])->find();
            $crr['zoneName'] = $c3['region_name'];
        } else {
            $this->error("地址有误,请重新填写!",U('Users/address'));
            $crr['zoneName'] = "";
        }

        //微信支付的价格
        $wxCountPrice = $countPrice - $countPromotePrice;

        //门店自提的 门店信息
        $sellerIDsession=session("seller_id");
        if($sellerIDsession!="")
        {
            $yanG1=$this->Seller->where("id=".$sellerIDsession)->find();
            $this->assign("yanG1",$yanG1);
        }else{  //如果sesserIDsession 为空，说明用户所在位置超出任何一家店面的范围，此种情况是不能提供送货
            $yanG2=$this->Seller->select();
            $this->assign("yanG1Arr",$yanG2);
            $this->assign("sellerID","none");  // 当没有最近商家时，给前段传递一个none 的值
        }
        // 门店自提的优惠之后的价格
        $ztPrice=1;    //  自提优惠的价格
        $ztCountPrice = $countPrice - $ztPrice;

        $this->assign("ztPrice",$ztPrice);   // 将自提优惠的价格输出到页面
        $this->assign("ztCountPrice",$ztCountPrice);   // 自提优惠后的总价格

        $this->assign("wxCountPrice", $wxCountPrice);
        $this->assign("address", $crr);
        $this->assign("countPromotePrice", $countPromotePrice);
        $this->assign("countPrice", $countPrice);
        $this->assign("arr", $arr);
        $this->display("buy");
    }

    /*
     * 通过ajax传过来 商品的ID
     * $_POST['productID'] 为商品的ID
     * */
    function updateNum()
    {
        $data['id'] = '';
        $data['user_id'] = $this->userID;    //临时设置一个userID
        $data['goods_id'] = $_POST['productID'];    // 商品的DI

        /*通过productID找到对应商品的信息*/
        $arr = $this->Goods->where("id=" . $data['goods_id'])->find();   // 取得商品信息
        $data['goods_sn'] = $arr['goods_sn'];
        $data['name'] = $arr['name'];
        $data['market_price'] = $arr['market_price'];
        $data['shop_price'] = $arr['shop_price'];
        $data['promote_price'] = $arr['promote_price'];

        if ($_POST['name'] > $arr['number']) {
            echo "库存数量不足！！！";
            exit;
        } else {
            $data['number'] = $_POST['number'];    //  改变之前购物车此商品的购买数量
        }

        /*
         * 将数据存入购物车
         * */

        //1.从购物车表中找出goods_id 的商品

        $cond['goods_id'] = $data['goods_id'];    // 此处的goods_id 也就是ajax 传递过来的product_id
        $cond['user_id'] = $data['user_id'];
        $brr = $this->Cart->where($cond)->find();
        if (empty($brr))      // 判断一下购物车中是否已经存在这个商品
        {
            // 购物车中没有goods_id 这个商品 ,  第一次往购物车中添加
            $this->Cart->data($data)->add();
        } else {
            //  购物车中已经有goods_id 这个商品, 只需要改变 number 这个字段的值
            $save['number'] = $data['number'];
            $this->Cart->where("id=" . $brr['id'])->data($save)->save();
            $thisPrice = $data['shop_price'] * $data['number'];    // $price 为当前单一产品的价格
            $thisPromotePrice = $data['promote_price'] * $data['number'];
        }

        $cart['Num'] = $this->Cart->where("user_id=" . $data['user_id'])->sum('number');

        //计算购物车中的商品总价
        $yanGone = $this->Cart->where("user_id=" . $data['user_id'])->select();
        $price = '';
        $countPromotePrice = '';
        foreach ($yanGone as $key => $ro) {
            $price += $ro['number'] * $ro['shop_price'];
            $crr = $this->Goods->where("id=" . $ro['goods_id'])->find();
            $countPromotePrice += $ro['number'] * $crr['promote_price'];
        }
        $cart['price'] = $price;

        $wxCountPrice = $cart['price'] - $countPromotePrice;

        $cart1 = $cart['Num'] . "/" . $cart['price'] . "/" . $thisPrice . "/" . $thisPromotePrice . "/" . $countPromotePrice . "/" . $wxCountPrice;   //总数量/总价格/单个商品的总价/单个商品优惠的价格/优惠总价格
        echo $cart1;
        exit;
    }

    //生成订单
    function order()
    {
        if ($_POST) {
            // 判断 商品是否为空

            if($_POST['goods']=="")
            {
                $this->success("请选择您要购买的商品",U('Index/lbs'));
            }

            //  第一：将数据存入 order_info 表中
            $data['id'] = '';
            $data['order_sn'] = time().date("YmdHis");  // 订单号
            $data['user_id'] = $this->userID;
            $data['order_status'] = "0";    // 未付款
            $data['pay_status'] = "0";    // 未发货
            $data['consignee'] = $_POST['consignee'];
            $data['country'] = "中国";
            $data['province'] = "北京";
            $data['city'] = "北京";
            $data['zone'] = $_POST['zoneName'];
            $data['address'] = $_POST['address'];
            $data['mobile'] = $_POST['tel'];
            if($data['mobile']=="")
            {
                $this->error("联系方式有错误","Order/cart");
            }
            $data['pay_type'] = $_POST['pay_type'];    // 等于“0”时，货到付款

            if ($data['pay_type'] == 0) {
                $data['goods_amount'] = $_POST['cartPriceInput'];     // 非微信支付
            }
            elseif($data['pay_type']==1)
            {
                $data['goods_amount'] = $_POST['wxCountPrice'];    // 微信支付
            }

            $data['shipping_type']=$_POST['shipping_type'];

            // 如果选择门店自提，那么总价格再减去 自提的优惠价格
            // shipping_type 当等于"0"表示“送货上门”  等于“1”时表示“门店自提”
            if($data['shipping_type']==1)
            {
                $data['goods_amount']=$data['goods_amount']-$_POST['ztPriceInput'];
                if($_POST['sellerID']=="")      // 选择了门店自提的情况下，要选择具体的那一家店面, 如果么有选择店面返回之前的页面重新选择
                {
                    $this->error("请选择具体门店".'Order/cart');
                }
            }

            print_r($_POST['sellerID']);

            if($_POST['sellerID']=="")
            {
                echo "未知错误"; exit;
            }else{
                $data['seller_id']=$_POST['sellerID'];   // 在任何时候sellerID 这个值都是存在的
            }

            $data['shipping_fee'] = "";
            $data['add_time'] = time();
            $data['pay_time'] = "";
            $data['shipping_time'] = "";
            $aa = $this->orderInfo->data($data)->add();   // $aa 返回了 此条订单的ID  ，
            // 加入orderInfo表结束;
            //echo $data['order_sn']."--订单的编号---".$aa."--订单ID---";   exit;

            // 第二：orderGoods 表的操作 开始
            foreach ($_POST['goods'] as $r) {
                $gidAndNum = explode("/", $r);
                $dataa['id'] = '';
                $dataa['order_id'] = $aa;
                $dataa['goods_id'] = $gidAndNum[0];   //  goods_id
                $dataa['goods_number'] = $gidAndNum[1];    //  数量num
                $this->orderGoods->data($dataa)->add();
            }
            // orderGoods 表的操作 结束
            $yanGrady=new \Org\Util\yyf;

            // 此短信发送给用户；
            $contents="欢迎选购【稻道工厂】,您的订单号为{$data['order_sn']}";
            $yanGrady->sms($data['mobile'],$contents);
            // END

            // 此短信发送给商户；
            $sellerTel=$this->Seller->field("tel")->where("id=".$_POST['sellerID'])->find();  // 通过sellerID 得到所选商户的手机号；
            if($sellerTel['tel']!="")
            {
                $contentForSeller="您有一条新的订单,订单号为{$data['order_sn']},请在您的后台查看跟踪";
                $yanGrady->sms($sellerTel['tel'],$contentForSeller);
            }
            // END
            $this->zz($_POST['pay_type'], $data['order_sn'],$data['goods_amount'],$aa);
        }
    }

    function orderUpdate()
    {
        $this->zz($_POST['pay_type'],$_POST['order_sn'],$_POST['goods_amount'],$_POST['order_id']);
    }

    // $t1=支付方式 ；  $t2=订单编码 ;  $t3=商品总价 ;  $t4=订单ID；
    function zz($t1 = '', $t2 = '',$t3='',$t4='',$tel='')
    {
        if ($t1 == "0") {;
            $this->success("货到付款成功，专跳至[我的订单 ]",U('Users/myOrder'));
        } elseif ($t1 == "1") {
            header("Location:http://ddgc.dashipin.com/wxpay/example/jsapi.php?order_sn=".$t2."&goods_amount=".$t3."&order_id=".$t4);
        } elseif ($t1 == "2") {  // 2015-7-27  目前没有没有 支付状态为“2”的这个值，暂时没用
            header("Location:http://ddgc.dashipin.com/wxpay/example/jsapi.php?order_sn=".$t2."&goods_amount=".$t3."&order_id=".$t4);
        }
    }

//
//    public function getcode()
//    {
//        include_once('/Data/WxPayPubHelper/WxPayPubHelper.php');
//        $jsApi = new JsApi_pub();
//        $url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
//        Header("Location:".$url);
//    }

    public function wxPayOne($order_sn='')
    {
        Layout(false);

        $arr=$this->orderInfo->where("order_sn=".$order_sn)->find();
        $total_fee=explode(".",$arr['goods_amount']);;

        require_once APP_PATH."/WxpayAPI/lib/WxPay.Api.php";
        require_once APP_PATH."/WxpayAPI/example/WxPay.JsApiPay.php";
        require_once APP_PATH.'/WxpayAPI/example/log.php';

        $logHandler= new \CLogFileHandler(APP_PATH."/WxpayAPI/logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);

        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid($order_sn);  // 获得用户的openid ，   order_sn是订单编码，在这使用，是因为有一个回调
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("大食品");
        $input->SetAttach("");
//        $input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOut_trade_no($order_sn);
//        $input->SetTotal_fee($total_fee[0]);
        $input->SetTotal_fee(1);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://ddgc.dashipin.com/index.php/Home/Order/payOk");
//        $input->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);

        $order = \WxPayApi::unifiedOrder($input);
        echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        foreach($order as $key=>$value){
            echo "<font color='#00ff55;'>$key</font> : $value <br/>";
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();
        $this->assign("jsApiParameters",$jsApiParameters);
        $this->assign("editAddress",$editAddress);
        $this->assign("total_fee","1");
        $this->display();
        //③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
        /**
         * 注意：
         * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
         * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
         * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
         */

    }


    /*
     * 处理交易成功的订单，
     * 1：删除购物车中的数据；
     * ２：修改order_info表中的　pay_status　字段
     * */
    public function payOk()
    {
//        print_r($_GET);
        $order_id=$_GET['order_id'];
        $data['pay_status']="2";
        $this->orderInfo->where("id=".$order_id)->save($data);   //   修改pay_status字段为2  表示已经支付
        $this->Cart->where("user_id=".$this->userID)->delete();

        $this->success("交易成功",U('Users/myOrder'));
    }
}